package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;

    /**
     * 登录
     */
    @RequestMapping("/msmLogin")
    public Result msmLogin(@RequestBody Map<String, String> map) {
        try {
            //获取手机号 验证码
            String telephone = map.get("telephone");
            String validateCodeInParam = map.get("validateCode");

            //从Redis中获取到验证码
            String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_LOGIN + "-" + telephone);

            /*
                如果验证码不正确，返回结果
                判断是否是会员（通过手机号查询member表）
                    不是会员，自动注册为会员。
                    是会员，登录成功
             */
            //手机号和验证码都不能为NULL
            if (telephone == null || validateCodeInParam == null) {
                return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
            }

            //验证码校验
            if (!(validateCodeInParam != null && validateCodeInParam.equals(validateCodeInRedis))) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }

            memberService.msmLogin(telephone);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ACTION_FAIL);
        }
    }

}